package com.fiveGroup.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fiveGroup.pojo.User;
import com.fiveGroup.pojo.vo.DataVo;
import com.fiveGroup.service.UserService;
import com.fiveGroup.util.OSSUtils;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;


//用户管理控制层
@RestController
@RequestMapping("/api/user")
@Slf4j
public class BackgroundUserCommonController {

    //头像上传目录
    private static final String UPLOAD_DIR = "D:\\删除实验\\avatars\\";
    @Autowired
    private UserService userService;
    @Autowired
    private OSSUtils ossUtils;


    //分页和模糊查询用户名去获取所有用户
    @GetMapping("/getUser")
    public DataVo getUser(@RequestParam(defaultValue = "1") Integer page,
                          @RequestParam(defaultValue = "5") Integer pageSize,
                          @RequestParam(name = "username", required = false) String name) {

        IPage<User> userIPage = new Page<>(page, pageSize);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //name不为空才去条件查询
        if (StringUtils.hasText(name)) {
            queryWrapper.like("username", name);
        }
        userService.page(userIPage, queryWrapper);
        return DataVo.success(userIPage);
    }

    //新增用户
    @PostMapping("/addUser")
    public DataVo addUser(@RequestBody @Valid User user) {
        //密码加密
        String rawPassword = user.getPassword();
        String encryptedPassword = BCrypt.hashpw(rawPassword, BCrypt.gensalt());
        user.setPassword(encryptedPassword);

        //设置默认状态：0-正常
        if (user.getStatus() == null) {
            user.setStatus(0); // 正常
        }

        //设置默认实名认证状态：0-未认证
        if (user.getIsVerified() == null) {
            user.setIsVerified(0); // 未认证
        }
        //设置创建时间和更新时间为当前时间
        Date now = new Date();
        user.setCreatedAt(now);
        user.setUpdatedAt(now);

        boolean success = userService.save(user);
        if (success) {
            return DataVo.success("新增用户成功！");
        } else {
            return DataVo.fail("新增用户失败");
        }
    }

    //删除用户信息
    @DeleteMapping("/deleteUser")
    public DataVo deleteUser(@RequestParam(required = false) Long id,
                             @RequestParam(required = false) String ids) {
        //将批量删除和单次删除放在一个方法中
        if (id != null) {
            //单次删除
            //优化----根据登录管理员的权限决定是否删除用户？
            boolean success = userService.removeById(id);
            if (success) {
                return DataVo.success("删除成功");
            } else {
                return DataVo.fail("删除失败，用户可能不存在");
            }
        } else if (ids != null && !ids.trim().isEmpty()) {
            // 批量删除：ids 是类似 "1,2,3" 的字符串
            String[] idArray = ids.split(",");
            // 转成 Long 列表
            java.util.List<Long> idList = new java.util.ArrayList<>();
            for (String s : idArray) {
                try {
                    idList.add(Long.parseLong(s.trim()));
                } catch (NumberFormatException e) {
                    // 忽略非法ID格式
                    continue;
                }
            }
            if (idList.isEmpty()) {
                return DataVo.fail("没有有效的ID用于批量删除");
            }
            boolean success = userService.removeByIds(idList);
            if (success) {
                return DataVo.success("批量删除成功，共删除 " + idList.size() + " 条记录");
            } else {
                return DataVo.fail("批量删除失败");
            }
        } else {
            return DataVo.fail("请传入 id 或 ids 参数");
        }
    }

    //修改用户信息
    //修改真实姓名，邮箱，手机号，然后更新最新操作的时间
    @PostMapping("/updateUser")
    public DataVo updateUser(@RequestBody User user) {
        //判断该用户是否存在
        if (user.getId() == null) {
            return DataVo.fail("用户ID不能为空");
        }
        User newUser = userService.getById(user.getId());
        newUser.setRealname(user.getRealname());
        newUser.setEmail(user.getEmail());
        newUser.setPhone(user.getPhone());
        //更新用户的操作时间
        Date now = new Date();
        newUser.setUpdatedAt(now);
        boolean success = userService.updateById(newUser);
        if (success) {
            return DataVo.success("用户信息更新成功");
        } else {
            return DataVo.fail("用户信息更新失败，可能用户不存在");
        }
    }

    //头像上传（使用阿里云 OSS）
    @PostMapping("/uploadAvatar")
    public DataVo<String> uploadAvatar(
            @RequestParam("file") MultipartFile file,
            @RequestParam("userId") Long userId) {

        if (file.isEmpty()) {
            return DataVo.fail(400, "上传文件不能为空");
        }

        String contentType = file.getContentType();
        if (contentType == null || (!contentType.startsWith("image/jpeg") && !contentType.startsWith("image/png"))) {
            return DataVo.fail(400, "只允许上传 JPG 或 PNG 格式的图片");
        }

        long maxSize = 2 * 1024 * 1024;
        if (file.getSize() > maxSize) {
            return DataVo.fail(400, "图片大小不能超过 2MB");
        }

        // 获取当前用户
        User user = userService.getById(userId);
        if (user == null) {
            return DataVo.fail(404, "用户不存在，userId: " + userId);
        }

        try {
            // 调用 OSS 工具类上传文件
            String avatarUrl = ossUtils.upload(file.getOriginalFilename(), file.getBytes());

            // 添加日志，查看上传返回的URL
            log.info("OSS上传成功，返回URL: {}", avatarUrl);

            // 更新用户头像 URL 到数据库
            user.setAvatar(avatarUrl);
            boolean success = userService.updateById(user);

            if (success) {
                // 确保返回的data字段是字符串格式
                return DataVo.success("头像上传成功:" + avatarUrl);
            } else {
                return DataVo.fail(500, "头像上传成功，但更新用户信息失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return DataVo.fail(500, "头像上传失败：" + e.getMessage());
        }
    }
}
